package cmd

import (
	"flag"
	"fmt"
	"os"
)

type KillCommand struct {
	fs   *flag.FlagSet
	port int
	pid  int
	path string
}

func NewKillCommand() *KillCommand {
	kc := &KillCommand{
		fs: flag.NewFlagSet("kill", flag.ExitOnError),
	}
	kc.fs.IntVar(&kc.port, "port", 0, "Port number to kill process")
	kc.fs.IntVar(&kc.pid, "pid", 0, "Process ID to kill")
	return kc
}

func (k *KillCommand) Name() string {
	return k.fs.Name()
}

func (k *KillCommand) Init(args []string) error {
	return k.fs.Parse(args)
}

func (k *KillCommand) Run() error {
	if k.pid != 0 {
		return KillProcessByPID(k.pid)
	}

	if k.port != 0 {
		return KillProcessByPort(k.port)
	}

	if k.path != "" {
		return KillProcessByPath(k.path)
	}
	return nil
}

func (k *KillCommand) Check() error {
	if k.port == 0 && k.pid == 0 && k.path == "" {
		return fmt.Errorf("must specify either -port or -pid or -path")
	}
	return nil
}

func (k *KillCommand) Usage() {
	fmt.Fprintf(os.Stderr, "Usage: %s kill [options]\n", os.Args[0])
	fmt.Fprintln(os.Stderr, "Options:")
	k.fs.PrintDefaults()
	fmt.Fprintln(os.Stderr, "\nExamples:")
	fmt.Fprintln(os.Stderr, "  Kill process by port: cmd-manager kill -port 8080")
	fmt.Fprintln(os.Stderr, "  Kill process by PID:  cmd-manager kill -pid 1234")
}
